package com.moogene.android.engine.animlite;

import android.util.Log;

public class RotateAnim extends Anime {
	private String TAG = "RotateAnim";
	public static final int INFINITE = -1;
	public static final int ZERO = -2;
	public static final int USE_CURRENT = -3;

	private float mDegreeDest;
	private float mDegreeStep;

	RotateAnim(DrawableWrapper drawableWrapper) {
	    super(drawableWrapper);
	}

    public void setPivot(float px, float py) {
		drawableWrapper.setRotatePivot(px, py);
	}

    public void setRelativePivot(float px, float py){
        drawableWrapper.setRelativeRotatePivot(px, py);
    }

	public void start(float toDegree, float stepDegree) {
		float begin = drawableWrapper.getRotateDegree();
		start(begin, toDegree, stepDegree);
	}

	public void start(float fromDegree, float toDegree, float stepDegree) {
		start();
		mDegreeDest = toDegree;
		mDegreeStep = stepDegree;
		drawableWrapper.setRotateDegree(fromDegree);
	}

	public void setDegree(float toDegree){
	    drawableWrapper.setRotateDegree(toDegree);
	}
	
	public void setDegree(int toX, int toY, int fromX, int fromY){
		double angrad = Math.atan2(toY - fromY, toX - fromX);
		double degree = Math.toDegrees(angrad) + 180;
	    drawableWrapper.setRotateDegree((float)degree);
	}

	@Override
	public void stop(){
		super.stop();
		drawableWrapper.setRotateDegree(0);
	}

	public float getCurDegree() {
		return drawableWrapper.getRotateDegree();
	}

	/* When same of anim rotate to same degree, lock it for better performance */
	/* !!should have bugs when using this interface, related to canvas.save(), should be fixed later*/
	public static void lockRotate() {
		DrawableWrapper.lockRotate();
	}

	public static void unlockRotate() {
		DrawableWrapper.unlockRotate();
	}

	@Override
	boolean nextFrame() {
		if (!super.nextFrame()) {
			return false;
		}
		float curDegree = drawableWrapper.getRotateDegree();
		if (mDegreeStep != 0) {
			curDegree += mDegreeStep;
			drawableWrapper.setRotateDegree(curDegree);
			if (mDegreeDest == INFINITE) {
				return true;
			}
			if ((mDegreeStep > 0 && curDegree >= mDegreeDest)
					|| (mDegreeStep < 0 && curDegree <= mDegreeDest)) {
				pause();
				Log.i(TAG, "Pause because reach the dest.");
				return false;
			}
		}
		return true;
	}
}
